let router = require('koa-router')();
let Order = require('../models/order.js');
let Cart = require('../models/cart.js');
let sha1 = require('sha1');
router.prefix('/order');

/**
 * 生成订单
 */
router.post('/createOrder', async (ctx, next) => {
  try {
    let { ids = [], price = 0 } = ctx.request.body;
    if (ids.length === 0) {
      throw new Error('缺少参数');
    } else {
      let username = '';
      let arr = [];
      let orderId = sha1(`${Date.now()}-${ctx.userId}`);
      for (let i = 0; i < ids.length; i++) {
        let cart = await Cart.findOne({_id: ids[i]});
        username = cart.username;
        arr.push({
          original_title: cart.film.original_title,
          coverurl: cart.film.coverurl,
          collect_count: cart.film.collect_count,
          wish_count: cart.film.wish_count,
          genres: cart.film.genres,
          price: cart.film.price,
          doubanId: cart.doubanId,
          poster: cart.film.poster
        });
      }
      await Order.create({orderId, userId: ctx.userId, films: arr, username, price});
      ctx.success({orderId});
    }
  } catch (err) {
    throw err;
  }
});

/**
 * 根据订单id偶去订单详情
 */
router.get('/getOrder', async (ctx, next) => {
  try {
    let { orderId } = ctx.query;
    let order = await Order.findOne({orderId});
    ctx.success(order);
  } catch (err) {
    throw err;
  }
});

/**
 * 支付
 */
router.post('/pay', async (ctx, next) => {
  try {
    let { method, id } = ctx.request.body;
    await Order.updateOne({orderId: id, userId: ctx.userId}, {$set: {payMethod: method, status: 1}});
    let list = await Order.findOne({orderId: id});
    for (let i = 0; i < list.films.length; i++) {
      let item = list.films[i];
      await Cart.deleteOne({doubanId: item.doubanId, userId: ctx.userId});
    }
    ctx.success(`支付成功`);
  } catch (err) {
    throw err;
  }
});

/**
 * 获取我的订单列表
 */
router.get('/getMyOrder', async (ctx, next) => {
  try {
    let orders = await Order.find({userId: ctx.userId}).select('films status orderId');
    let arrs = orders.map(item => ({films: item.films, status: item.status, orderId: item.orderId}));
    let brrs = [];
    arrs.forEach(item => {
      item.films.forEach(sub => {
        sub._doc.status = item.status;
        sub._doc.orderId = item.orderId;
      });
      brrs = brrs.concat(item.films);
    });
    ctx.success(brrs);
  } catch (err) {
    throw err;
  }
});

/**
 * 获取订单列表
 * @type {[type]}
 */
router.get('/getOrders', async (ctx, next) => {
  try {
    let { name, orderId, startDate, endDate, page = 1, size = 10 } = ctx.query;
    page = +page;
    size = +size;
    let obj = {};
    name && (obj.username = name);
    orderId && (obj.orderId = orderId);
    if (startDate) {
      obj.createdAt = {$gte: new Date(startDate), $lte: new Date(endDate)};
    }
    let orders = await Order.find(obj).skip((page - 1) * size).limit(size).select('-films');
    let count = await Order.find({}).countDocuments();
    ctx.success({data: orders, count});
  } catch (err) {
    throw err;
  }
});
module.exports = router;
